package com.hh.releasenode.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.hh.releasenode.exception.RNException;
import com.hh.releasenode.entity.SysCaptchaEntity;
import com.hh.releasenode.dao.SysCaptchaDao;
import com.hh.releasenode.service.SysCaptchaService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * @ClassName SysCaptchaServiceImpl
 * @Description 验证码service实现类
 * @Author KunxianLi
 * Date 2020/6/2 13:58
 * Version 1.0
 **/
@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaDao,SysCaptchaEntity> implements SysCaptchaService {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if(StringUtils.isBlank(uuid)){
            throw  new RNException("uuid不能为空");
        }
        String code = defaultKaptcha.createText();

        SysCaptchaEntity captcha = this.getById(uuid);
        if(null == captcha){
            captcha = new SysCaptchaEntity();
            captcha.setUuid(uuid);
        }
        captcha.setCode(code);
        captcha.setExpireTime(DateUtils.addMinutes(new Date(),5));
        this.saveOrUpdate(captcha);

        return defaultKaptcha.createImage(code);

    }

    @Override
    public boolean validate(String uuid, String captcha) {
        SysCaptchaEntity sysCaptacha = this.getById(uuid);
        if(null == sysCaptacha){
            return false;
        }
        this.removeById(uuid);

        if(!sysCaptacha.getCode().equals(captcha)){
            return false;
        }

        if(sysCaptacha.getExpireTime().compareTo(new Date()) < 0){
            return false;
        }
        return true;
    }
}
